<?php
/*
 * 前台交易控制器
 */
class TradeController extends BasicController {
    
    private function init(){
        Yaf_Registry::get('tokenPlugin')->checkAuth(true);
    }

    /*
    * 激活码购买点击确定提交 Api
    */
    public function enkeycommitAction(){
        $params = $this->getPost();
        
        $grade = isset($params['grade']) ? $params['grade'] : 0;
        $type = isset($params['type']) ? $params['type'] : 0;
        $way = isset($params['way']) ? $params['way'] : 1;//支付方式：1 支付宝 2 人工收款 3 支付宝网银支付
        $user_id = G_USER_ID;
        
        $return['code'] = "1";
        $return['msg'] = '操作失败！';
        $return['data'] = [];
        
        if(!$grade || !$type || !$user_id || !$way
                || !in_array($grade, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12])
                        || !in_array($type, [1, 2, 3, 4])){//没有传递要查询的参数
            $return['code'] = "2";
            $return['msg'] = '参数错误';
            
            echo json_encode($return);
            return false;
        }
        
        // 1. 获取该年及对应该时长的激活码价格
        $ActivationkeyPriceModel = Helper::load('Activationkey_price');
        
        $info = $ActivationkeyPriceModel->Where(['ap_grade' => $grade, 'ap_type' => $type, 'is_valid' => 1])->SelectOne();
        
        if(!$info){//找不到 / 无效
            $return['code'] = "3";
            $return['msg'] = '没有对应的价格设置，请联系客服';
            
            echo json_encode($return);
            return false;
        }
        
        $price = $info['ap_price'];//激活码价格
        
        // 2.生成对应的激活码 $activationkey
        $ActivationkeyModel = Helper::load('Activationkey');
        $activationkey = build_activationkey();
        
        $adata = [
            'a_key'     => $activationkey,
            'a_type'    => $type,
            'a_price'   => $price,
            'is_online' => 1,
            'is_valid'  => 0,//暂时置为无效，待成功购买之后置为有效
            'ctime'     => CUR_TIMESTAMP,
            'mtime'     => CUR_TIMESTAMP
        ];

        $r = $ActivationkeyModel->Insert($adata);
        if(!$r){//生成失败
            $return['code'] = "4";
            $return['msg'] = '服务器异常，生成激活码失败';
            
            echo json_encode($return);
            return false;
        }
        
        // 3.生成对应的订单
        $tradeenModel = Helper::load('Trade_en');
        
        $tm_out_trade_no = '0512'.date('YmdHis').rand(1000, 9999);
        
        $data = [
            'user_id'           => $user_id,
            'tm_out_trade_no'   => $tm_out_trade_no,
            'tm_youhui'         => 0,
            'tm_total_price'    => $price,
            'tm_total_fee'      => $price,
            'tm_activationkey'  => $activationkey,
            'tm_grade'          => $grade,
            'tm_way'            => $way,
            'ctime'             => CUR_TIMESTAMP,
            'mtime'             => CUR_TIMESTAMP
        ];
        
        $rr = $tradeenModel->Insert($data);
        if(!$rr){//生成失败
            $return['code'] = "5";
            $return['msg'] = '服务器异常，生成订单失败';
            
            echo json_encode($return);
            return false;
        }
        
        if($way == 1){
            // 4.调用支付宝接口程序
            Yaf_Loader::import(LIB_PATH.'/alipay/alipay.config.php');
            Yaf_Loader::import(LIB_PATH.'/alipay/lib/alipay_submit.class.php');
            
            $cateModel = Helper::load('Cate');

            //激活码时长分类
            $enTypeArr = $cateModel::$enTypeArr;
            //激活码年级分类
            $enGradeArr = $cateModel::$enGradeArr;
            
            $parameter = [
                "service"           => $alipay_config['service'],
                "partner"           => $alipay_config['partner'],
                "seller_id"         => $alipay_config['seller_id'],
                "payment_type"      => $alipay_config['payment_type'],
                "notify_url"        => 'http://webapi.jxzhjy.com/default/alipay/ennotify',
                "return_url"        => '',

                "anti_phishing_key" =>$alipay_config['anti_phishing_key'],
                "exter_invoke_ip"   =>$alipay_config['exter_invoke_ip'],
                "out_trade_no"      => $tm_out_trade_no,//商户订单号，商户网站订单系统中唯一订单号，必填
                "subject"           => '[支付宝-嘉兴智慧教育在线课堂][人机英语]['.$enGradeArr[$grade].']['.$enTypeArr[$type].'][网上支付]['.$tm_out_trade_no.']',//订单名称，必填
                "total_fee"         => $price,//付款金额，必填
                "body"              => '',//商品描述，可空
                "_input_charset"    => trim(strtolower($alipay_config['input_charset']))
            ];

            //建立请求
            $alipaySubmit = new AlipaySubmit($alipay_config);
            $return['data']['url'] = $alipaySubmit->buildRequestUri($parameter);

            $return['code'] = '0';
            $return['msg'] = '操作成功';
        }
        else{
            $return['code'] = "6";
            $return['msg'] = '暂未支持该渠道支付方式';
        }
        
        echo json_encode($return);
        return false;
    }
    
}